package com.ruoyi.consumer.task;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.consumer.domain.CStatisticTable;
import com.ruoyi.consumer.domain.WxConfig;
import com.ruoyi.consumer.service.impl.CStatisticSumTableServiceImpl;
import com.ruoyi.consumer.service.impl.CStatisticTableServiceImpl;
import com.ruoyi.consumer.utils.pay.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.ruoyi.consumer.constance.ApiConstance.URL_PREFIX;

@Component("AccessTokenTask")
public class AccessTokenTask {

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CStatisticSumTableServiceImpl cStatisticSumTable;

    @Autowired
    private CStatisticTableServiceImpl cStatisticTable;

    //更新access token
    public void three() {
        System.out.println("three定时任务执行！");
        String grant_type = "client_credential";
        String params = "appid=" + wxConfig.getAppid() + "&secret=" + wxConfig.getAppSecret() + "&grant_type=" + grant_type;
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        JSONObject json = JSONObject.parseObject(sr);
        System.out.println("解析code请求结果:" + json.toString());
        String accessToken = json.getString("access_token");
        redisCache.setCacheObject("token:" + "findConsumerAccessToken", accessToken);
    }

    public void four() {
        System.out.println("four定时任务执行！");
        String grant_type = "client_credential";
        String params = "appid=" + wxConfig.getF_appid() + "&secret=" + wxConfig.getF_appSecret() + "&grant_type=" + grant_type;
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        JSONObject json = JSONObject.parseObject(sr);
        System.out.println("解析code请求结果:" + json.toString());
        String accessToken = json.getString("access_token");
        redisCache.setCacheObject("token:" + "findFillerAccessToken", accessToken);
    }

    public void five() {
        System.out.println("five定时任务执行！");
        String params = "appKey=" + wxConfig.getZLappKey() + "&appSecret=" + wxConfig.getZLappSecret();
        String sr = HttpRequest.sendGet(URL_PREFIX + "oauth/authorize", params);
        JSONObject json = JSONObject.parseObject(sr);
        JSONObject datas = json.getJSONObject("datas");
        // 提取 authorization 的值
        String authorization = datas.getString("authorization");
        System.out.println("Access Token: " + authorization);
        redisCache.setCacheObject("token:" + "authorizerAccessToken", authorization);
    }

    public void statisticSum() {
        System.out.println("statisticSum定时任务执行！");

        // 获取昨天的日期
        Date yesterday = DateUtils.getYesterdayDate();
        // 创建 CStatisticTable 对象并设置更新时间和 facilitId
        //查询昨天所有的数据
        CStatisticTable statisticTable = new CStatisticTable();
        statisticTable.setUpdateTime(yesterday);
        List<CStatisticTable> cStatisticTables = cStatisticTable.selectCStatisticTableList(statisticTable);
        List<String> fields = Arrays.asList("facilitId", "fuserId", "userId", "companyId", "magngerId", "leaderId", "carId");
        for (String field : fields) {
            processStatistic(cStatisticTables, yesterday, field);
        }
        System.out.println("statisticSum定时任务执行完成！");
    }

    public void processStatistic(List<CStatisticTable> cStatisticTables, Date yesterday, String field) {
        Set<Integer> idSet = new HashSet<>();
        System.out.println("idSet" + field);
        // 遍历昨天所有的数据
        for (CStatisticTable table : cStatisticTables) {
            if ("facilitId".equals(field)) {
                idSet.add(table.getFacilitId());
            } else if ("userId".equals(field)) {
                idSet.add(table.getUserId());
            } else if ("companyId".equals(field)) {
                idSet.add(table.getCompanyId());
            } else if ("fuserId".equals(field)) {
                idSet.add(table.getFuserId());
            } else if ("magngerId".equals(field)) {
                idSet.add(table.getMangerId());
            } else if ("leaderId".equals(field)) {
                idSet.add(table.getLeaderId());
            } else if ("carId".equals(field)) {
                idSet.add(table.getCarId());
            }
        }
        // 现在 idSet 中包含了所有不重复的 ID ,接下来去除重复的
        List<Integer> uniqueIds = new ArrayList<>(idSet);
        System.out.println("统计类目" + field + ": uniqueIds" + uniqueIds);
        //遍历当天所有数据
        for (int i = 0; i < uniqueIds.size(); i++) {
            CStatisticTable statisticTable1 = new CStatisticTable();
            if ("facilitId".equals(field)) {
                statisticTable1.setFacilitId(uniqueIds.get(i));
            } else if ("userId".equals(field)) {
                statisticTable1.setUserId(uniqueIds.get(i));
            } else if ("companyId".equals(field)) {
                statisticTable1.setCompanyId(uniqueIds.get(i));
            } else if ("fuserId".equals(field)) {
                statisticTable1.setFuserId(uniqueIds.get(i));
            } else if ("magngerId".equals(field)) {
                statisticTable1.setMangerId(uniqueIds.get(i));
            } else if ("leaderId".equals(field)) {
                statisticTable1.setLeaderId(uniqueIds.get(i));
            } else if ("carId".equals(field)) {
                statisticTable1.setCarId(uniqueIds.get(i));
            }
            statisticTable1.setUpdateTime(yesterday);
            List<CStatisticTable> cStatisticTables1 = null;
            if ("facilitId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayFacilitIdOrderFilledSum(statisticTable1);
            } else if ("userId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayUserIdOrderFilledSum(statisticTable1);
            } else if ("companyId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayCompanyIdOrderFilledSum(statisticTable1);
            } else if ("fuserId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayFuserIdOrderFilledSum(statisticTable1);
            } else if ("magngerId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayMagngerIdOrderFilledSum(statisticTable1);
            } else if ("leaderId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayLeaderIdOrderFilledSum(statisticTable1);
            } else if ("carId".equals(field)) {
                cStatisticTables1 = cStatisticSumTable.selectYesterdayCarIdOrderFilledSum(statisticTable1);
            }

            Long orderFilledSum = 0L;
            Long orderMoney = 0L;
            // 计算加注量之和
            if (cStatisticTables1.isEmpty()) {
                System.out.println("没有记录");
            } else {
                for (CStatisticTable cStatisticTable : cStatisticTables1) {
                    // 判断加注量是否为 null，若不为 null 则累加到加注量之和中
                    if (cStatisticTable.getOrderFilled() != null) {
                        orderFilledSum += cStatisticTable.getOrderFilled();
                        orderMoney += cStatisticTable.getOrderMoney();
                    }
                    if (cStatisticTable == cStatisticTables1.get(cStatisticTables1.size() - 1)) {
                        // 创建 SimpleDateFormat 对象，指定日期格式
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        // 使用 SimpleDateFormat 格式化日期
                        String formattedDate = sdf.format(yesterday);
                        saveStatisticSum(formattedDate, field, uniqueIds.get(i), orderFilledSum, orderMoney, cStatisticTables1.size());
                    }
                }
            }
        }
    }


    public void saveStatisticSum(String date, String category, int id, Long orderFilledSum, Long orderMoney, int total) {
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("orderFilledSum", orderFilledSum.toString());
        dataMap.put("orderMoney", orderMoney.toString());
        dataMap.put("total", String.valueOf(total));

        String key = String.format("StatisticSum:%s:%s:%d", date, category, id);
        redisCache.setCacheMap(key, dataMap);
    }

    public Map<String, Integer> getStatisticSum(String date, String category, int id) {
        String key = String.format("StatisticSum:%s:%s:%d", date, category, id);
        return redisCache.getCacheMap(key);
    }
}


